using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Client.view
{
    public partial class ClientForm : Form
    {
        Client client;
        public ClientForm()
        {
            InitializeComponent();
            client = new Client();
        }

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!client.isConnected())
            {
                client.Connect("localhost", 9999);
                client.Send("/name " + textBox1.Text);
                // Create thread
                Thread thread = new Thread(new ThreadStart(run));
                thread.IsBackground = true;

                // Start thread
                thread.Start();
            }
        }

        private void run()
        {
            try
            {
                string message;
                byte[] data;
                int length;
                while (true)
                {
                    data = new byte[256];
                    length = client.Receive(data);
                    message = Encoding.ASCII.GetString(data, 0, length);
                    client.receive(buffer);
                }
            }
            catch (Exception e)
            {
            }

        }

        private void disConnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (client.isConnected())
            {
                client.Send("/exit");
                client.Disconnect();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            client.Send(textBox3.Text);
        }

        private void ClientForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (client.isConnected())
            {
                client.Send("/exit");
                client.Disconnect();
            }
        }
    }
}